package com.isoft.service.impl;

import com.isoft.entity.DfoeDfdeEntity;
import com.isoft.mapper.DfoeDfdeMapper;
import com.isoft.service.DfoeDfdeService;
import com.isoft.util.XmlParserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Service
public class DfoeDfdeServiceImpl implements DfoeDfdeService {
    private static final Logger logger = LoggerFactory.getLogger(DfoeDfdeServiceImpl.class);

    @Autowired
    private DfoeDfdeMapper dfoeDfdeMapper;

    @Autowired
    private XmlParserUtil xmlParserUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(MultipartFile file) throws IOException {
        String xmlContent = new String(file.getBytes(), StandardCharsets.UTF_8);
        logger.info("Processing DFDE XML file: {}, size: {} bytes",
                file.getOriginalFilename(), file.getSize());
        return parseAndSave(xmlContent);
    }

    @Override
    public void parseAndSave(DfoeDfdeEntity entity) {
        processFlightData(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(String xmlContent) {
        try {
            if (xmlContent == null || xmlContent.trim().isEmpty()) {
                throw new IllegalArgumentException("XML content is empty");
            }

            DfoeDfdeEntity entity = xmlParserUtil.parseXml(xmlContent, DfoeDfdeEntity.class);

            if (entity == null || entity.getDflt() == null) {
                throw new IllegalArgumentException("Invalid DFDE XML structure");
            }

            processFlightData(entity);

            return "DFDE flight data processed successfully. Flight ID: " + entity.getDflt().getFlightId();
        } catch (Exception e) {
            logger.error("DFDE XML processing failed", e);
            throw new RuntimeException("Failed to process DFDE XML: " + e.getMessage());
        }
    }

    private void processFlightData(DfoeDfdeEntity entity) {
        dfoeDfdeMapper.insertMeta(entity);
        dfoeDfdeMapper.insertFlightBase(entity);

        // 检查是否已存在该航班的异常记录
        int count = dfoeDfdeMapper.countFlightIrregularity(entity.getDflt().getFlightId());
        if (count > 0) {
            // 更新现有记录
            dfoeDfdeMapper.updateFlightIrregularity(entity);
        } else {
            // 插入新记录
            dfoeDfdeMapper.insertFlightIrregularity(entity);
        }

        logger.info("DFDE data saved for flight ID: {}", entity.getDflt().getFlightId());
    }
}